import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

// 定义counter空间
export const useCityList = defineStore('cityList', () => {
    // 定义状态
    const cityList = ref([]);

    //当前页面查看的城市：用于识别是否存在
    const currentCity = ref({
        edcode: '',
        cityName: ''
    });

    //本地化存储
    const getCityList = () => {
        cityList.value = JSON.parse(localStorage.getItem('cityList')) || [];
    }
    // 初始获取本地存储
    getCityList();
    const setCityList = () => {
        localStorage.setItem('cityList', JSON.stringify(cityList.value));
    };

    const addCity = (adcode, cityName) => {
        cityList.value.push({
            id: new Date().getTime(),
            cityName: cityName,
            adcode: adcode
        });
        console.log(cityList.value);
        setCityList();
    }
    const removeCity = (id) => {
        cityList.value = cityList.value.filter(item => item.id !== id);
        setCityList();
    }

    const updataCurrentCity = (adcode, cityName) => {
        currentCity.value = {
            adcode: adcode,
            cityName: cityName
        }
    }
    //计算属性，当前城市是否在列表中
    const isCurrentCityInList = computed(() => {
        return cityList.value.some(
            (city) => city.adcode === currentCity.value.adcode
        );
    });
    return {
        cityList,//城市记录列表
        addCity,//添加城市
        removeCity,//删除城市
        currentCity,//当前页面查看的城市
        updataCurrentCity,//更新当前页面查看的城市
        isCurrentCityInList, //当前城市是否在列表中
    }
})